/*
 *      manager.cpp
 *      
 *      2009 Víctor Manuel Ochoa <kanito8a@gmail.com>
 *      
 *      This program is free software; you can redistribute it and/or modify
 *      it under the terms of the GNU General Public License as published by
 *      the Free Software Foundation; either version 2 of the License, or
 *      (at your option) any later version.
 *      
 *      This program is distributed in the hope that it will be useful,
 *      but WITHOUT ANY WARRANTY; without even the implied warranty of
 *      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *      GNU General Public License for more details.
 *      
 *      You should have received a copy of the GNU General Public License
 *      along with this program; if not, write to the Free Software
 *      Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 *      MA 02110-1301, USA.
 */


#include "manager.h"


Manager::Manager()
{
	
}


Manager::~Manager()
{
	
}

void Manager::freeMemory()
{
	list<Entity *>::iterator i;
			
	for(i=m_game_entities.begin();i!=m_game_entities.end();i++){
		(*i)->freeMemory();
		delete (*i);
	}
		
	m_game_entities.clear();
	
}

bool Manager::init()
{
	m_game_entities.clear();
	m_group_manager.init();
	
	return true;
}
/*
 * 
 * name: addEntity
 * Adds a new Entity. Order by Z
 * @param Entity
 */
void Manager::addEntity(Entity *_new_entity)
{	
	if(m_game_entities.empty())
	{
		m_game_entities.push_back(_new_entity);
		return;	
	}
		
	list<Entity *>::iterator i;
	for(i=m_game_entities.begin();(*i)->getZ()>_new_entity->getZ() && i!=m_game_entities.end();i++);
	
	m_game_entities.insert(i,_new_entity);	
}

/*
 * 
 * name: desconocido
 * @param
 * @return
 */
void Manager::update()
{
	list<Entity *>::iterator i;
	i=m_game_entities.begin();	
	
	while(i!=m_game_entities.end())
	{
		if((*i)->isAlive())
		{
			(*i)->update();
			++i;
		}
		else
		{
			(*i)->freeMemory();
			i=m_game_entities.erase(i);
		}	
	}
}

/*
 * 
 * name: desconocido
 * @param
 * @return
 */
void Manager::draw()
{
	glClear(GL_DEPTH_BUFFER_BIT|GL_COLOR_BUFFER_BIT);
	
	list<Entity *>::iterator i;
	for(i=m_game_entities.begin();i!=m_game_entities.end();i++)
	{
		(*i)->draw();
	}
}

